import { api } from "../ice/api";
import { code2Session, getPhoneNumber } from "../third/mp";
import { genAppToken } from "../../utils/jwt";

export async function bindMobile(body, userId) {
  const { phoneNumber: mobile } = await getPhoneNumber(body);
  const user = await api.getUserInfo(userId);
  if (!user) {
    throw "用户不存在";
  }
  await api.postUserInfo({
    id: userId,
    mobile,
    status: Math.max(2, user.status),
  });
  return {
    userId,
    mobile,
  };
}

export async function mpLogin({ js_code }, ip) {
  if (!js_code) {
    throw "缺少参数";
  }
  const { openid, ...session } = await code2Session(js_code);
  let user = await api.getUserInfo({
    openid,
  });
  if (!user) {
    user = await api.postUserInfo({
      ip,
      openid,
      ...session,
    });
  }
  const id = user.id;
  const token = genAppToken(id);
  return {
    id,
    token,
    status: user.status,
  };
}
